{% extends "../base.html" %}
{% load admin_utils %}

{% block main_content %}
<div id="application-processes-list" style="width: 100%;" class="p20">
    <bk-table
        :data="processes"
        >
        <bk-table-column type="expand" width="30">
            <template slot-scope="props">
                <bk-table :data="props.row.instances" :outer-border="false" :header-cell-style="{background: '#fff', borderRight: 'none'}">
                    <bk-table-column label="实例详情" type="expand" width="80" :before-expand-change="fetchInstanceEnvs(application.region, props.row.engine_app)">
                        <template slot-scope="props">
                            <bk-table :data="formatEnv(props.row.envs)" stripe virtual-render height="400px" :row-border="false" cell-class-name="envs" v-if="props.row.envs">
                                <bk-table-column label="key" prop="key"></bk-table-column>
                                <bk-table-column label="value" prop="value"></bk-table-column>
                            </bk-table>
                        </template>
                    </bk-table-column>
                    <bk-table-column prop="name" label="实例名称">
                        <template slot-scope="props">
                            $[ props.row.name.split("-").pop() ]
                        </template>
                    </bk-table-column>
                    <bk-table-column prop="state" label="状态"></bk-table-column>
                    <bk-table-column prop="ready" label="是否就绪">
                        <template slot-scope="props">
                            $[ props.row.ready ? '是' : '否' ]
                        </template>
                    </bk-table-column>
                    <bk-table-column prop="start_time" label="创建时间">
                        <template slot-scope="props">
                            创建于 <span>$[ props.row.start_time ]</span>
                        </template>
                    </bk-table-column>

                </bk-table>
            </template>
        </bk-table-column>
        <bk-table-column label="进程类型" prop="type">
            <template slot-scope="props">
                <span v-bk-tooltips="{content: props.row.command }">$[ props.row.type ]
                    <i class="bk-icon icon-info-circle-shape" style="color: #699df4" v-if="props.row.command"></i>
                </span>
            </template>
        </bk-table-column>
        <bk-table-column label="模块" prop="metadata.module"></bk-table-column>
        <bk-table-column label="环境" prop="metadata.env" align="center">
            <template slot-scope="props">
                $[ props.row.metadata.env | env2zh ]
            </template>
        </bk-table-column>
        <bk-table-column label="实例数" prop="environment" align="center">
            <template slot-scope="props">
                $[ props.row.available_instance_count ]/$[ props.row.desired_replicas ]
            </template>
        </bk-table-column>
        <bk-table-column label="资源方案" prop="process_spec.plan.name" v-if="application.type !== 'cloud_native'"></bk-table-column>
        <bk-table-column label="操作" v-if="application.type !== 'cloud_native'">
            <template slot-scope="props">
                <a class="bk-text-button mr10" href="javascript:void(0);" @click="editProcessSpecPlan(props.row)">修改资源方案</a>
                <a class="bk-text-button mr10" href="javascript:void(0);" @click="scale(props.row)" v-if="props.row.command !== null">调整实例数</a>
                <a class="bk-text-button mr10 is-disabled" href="javascript:void(0);" v-bk-tooltips="{content: '进程未运行, 无法调整实例数' }" v-else>调整实例数</a>
            </template>
        </bk-table-column>
    </bk-table>

    <bk-dialog v-model="dialog.visible" header-position="center" width="500" :confirm-fn="submitDialog">
        <div slot="header">
            调整 <b>[ $[ dialog.row.type ]进程 ]</b> $[ dialog.form.type ]
        </div>
        <div style="text-align: center" class="pb30">
            <span>模块: <b>$[ dialog.row.metadata.module ]</b></span>
            <span>环境: <b>$[ dialog.row.metadata.env | env2zh ]</b></span>
        </div>

        <bk-form :label-width="120" :model="dialog.form" :loading="dialog.loading">
            <bk-form-item label="资源方案" :required="true" v-if="dialog.form.type === '资源方案'">
                <div style="display: flex;align-items: center;">
                    <bk-select v-model="dialog.form.process_spec_plan_id" style="flex-grow: 1;" searchable>
                        <bk-option v-for="plan in processSpecPlanList"
                            :key="plan.id"
                            :id="plan.id"
                            :name="plan.name">
                        </bk-option>
                    </bk-select>
                    <span style="margin-left: 10px;cursor: pointer;"
                          class="bk-icon icon-plus-square"
                          @click="gotoCreateProcessSpecPlan"
                          v-bk-tooltips="{content: '新增资源方案', placements: ['right'] }"
                    ></span>
                </div>
            </bk-form-item>

            <bk-form-item label="进程实例数" :required="true" v-if="dialog.form.type === '实例数'">
                <bk-input v-model="dialog.form.target_replicas" type="number" :min="0" :max="dialog.row.process_spec.plan.max_replicas"></bk-input>
            </bk-form-item>
        </bk-form>
    </bk-dialog>

</div>
{% endblock %}

{% block main_script %}
<script>
    const application = {{ application | to_json }}

    const processes = {{ processes | to_json }}

    const URLRouter = {
        list: decodeURI("{% url 'wl_api.process_spec_plan' %}"),
        switch_process_plan: decodeURI("{% url 'wl_api.application.process_plan' '${engine_app_name}' '${process_type}' %}"),
        scale: decodeURI("{% url 'wl_api.application.process_scale' '${engine_app_name}' '${process_type}' %}"),
        retrieve: decodeURI("{% url 'wl_api.application.process_instance' '${engine_app_name}' '${process_type}' '${process_instance_name}' %}"),
    }


document.addEventListener('DOMContentLoaded', () => {
    new Vue({
        el: "#application-processes-list",
        delimiters: ['$[', ']'],
        mixins: [SubmitMixin],
        data: function () {
            return {
                application,
                processes,
                SEARCH_PARAM: 'search_term',
                filterKey: undefined,
                dialog: {
                    type: 'edit',
                    visible: false,
                    loading: true,
                    row: {
                        metadata: {

                        },
                        process_spec: {
                            plan: {
                                max_replicas: 5
                            }
                        }
                    }
                },
                processSpecPlanList: [],
                urlForCreatingprocessSpecPlan: '{% url "admin.process_spec_plan.manage" %}',
            }
        },
        methods: {
            scale: function (row) {
                this.dialog.row = row
                this.dialog.form.process_spec_plan_id = undefined
                this.dialog.form.target_replicas = row.desired_replicas

                this.dialog.form.type = "实例数"
                this.dialog.visible = true
            },
            editProcessSpecPlan: function (row) {
                this.dialog.row = row
                this.dialog.form.process_spec_plan_id = row.process_spec.plan.id
                this.dialog.form.target_replicas = undefined

                this.dialog.form.type = "资源方案"
                this.dialog.loading = true

                this.fetchprocessSpecPlanList(row).then(
                    data => {
                        this.dialog.visible = true
                        this.dialog.loading = false
                    }
                )
            },
            fillUrlTemplate: function (url_template, {form, row}) {
                if (form.type === '实例数' ) {
                    url_template = URLRouter['scale']
                } else if (form.type === '资源方案') {
                    url_template = URLRouter['switch_process_plan']
                }
              return url_template.replace("${engine_app_name}", row.engine_app)
                        .replace("${process_type}", row.type)
            },
            submitCallback: function () {
                if (this.dialog.form.process_spec_plan_id !== undefined) {
                    let selected_plan = this.processSpecPlanList.filter(item => item.id == this.dialog.form.process_spec_plan_id)[0]
                    if (selected_plan === undefined) {
                        window.location.reload()
                    } else {
                        this.dialog.row.process_spec.plan = selected_plan
                    }
                }
                if (this.dialog.form.target_replicas !== undefined) {
                    this.dialog.row.process_spec.target_replicas = this.dialog.form.target_replicas
                }
            },
            gotoCreateProcessSpecPlan: function () {
                let row = this.dialog.row
                let url = this.urlForCreatingprocessSpecPlan + "?" + querystring.stringify({
                    mode: 'create',
                    env: row.metadata.env,
                    region: this.application.region,
                    limits: btoa(JSON.stringify(row.process_spec.plan.limits)),
                    requests: btoa(JSON.stringify(row.process_spec.plan.requests)),
                })
                // 用于 sub windows 传参
                window.form = {
                    environment: row.metadata.env,
                    region: this.application.region,
                    limits: row.process_spec.plan.limits,
                    requests: row.process_spec.plan.requests,
                    max_replicas: row.process_spec.plan.max_replicas,
                    name: '[COPY]' + row.process_spec.plan.name
                }
                this.checkWindowClose(window.open(url,
                    '新增资源方案',
                    'height=800, width=800, top=200, left=400, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'),
                    300, () => this.fetchprocessSpecPlanList(row))
            },
            async checkWindowClose (win, sleepTime = 300, callback = () => undefined) {
                if (win.closed) {
                    callback()
                } else {
                    await new Promise(resolve => {
                        setTimeout(resolve, sleepTime)
                    })
                    this.checkWindowClose(win, sleepTime, callback)
                }
            },
            fetchprocessSpecPlanList: async function (row) {
                let query = {
                    offset:0, limit: 1000,
                }
                let prefix = window.location.href
                if (prefix.indexOf("?") > 0) {
                    query = {...querystring.parse(prefix.substr(prefix.indexOf("?") + 1)), ...query}
                }

                let data = await this.$http.get(URLRouter.list, {
                    params: query
                })
                this.processSpecPlanList = data.results
                return data
            },
            fetchInstanceEnvs: function (region, engine_app) {
                return async ({row, column}) => {
                    if (row.envs !== undefined) {
                        return true;
                    }
                    let url = URLRouter.retrieve.replace("${engine_app_name}", engine_app)
                            .replace("${process_type}", row.process_type)
                            .replace("${process_instance_name}", row.name)
                    let data = await this.$http.get(url)
                    row.envs = data.envs
                    return true
                }
            },
            formatEnv: function (envs) {
                return Object.keys(envs).map(key => {return {key, value: envs[key]}})
            }
        },
    })
})

</script>
<style>
    .bk-dialog-wrapper .bk-dialog-header {
        padding-bottom: 10px;
    }

    .bk-table .envs .cell {
        white-space: break-spaces;
        -webkit-line-clamp: revert;
        margin: 5px;
    }

</style>
{% endblock %}
